<template>
  <div class="container">
    <a-spin :spinning="pageLoading" tip="加载数据中...">
      <div class="head">
        <div class="head-left">
          <a-select
            v-model:value="selectedClass"
            placeholder="请选择班级"
            style="width: 300px"
            @change="selectClass"
            :field-names="{ label: 'className', value: 'classId' }"
            :options="classOptions"
            :disabled="pageLoading"
          >
            <template #option="{ classId, className }">
              <div class="class-option">
                {{ className }}
                <a-button
                  type="dashed"
                  @click.stop="showDeleteClassConfirm(classId, className)"
                  class="confirmButton"
                >
                  <template #icon>
                    <DeleteOutlined />
                  </template>
                </a-button>
              </div>
            </template>
            <template #dropdownRender="{ menuNode: menu }">
              <v-nodes :vnodes="menu" />
              <a-divider style="margin: 4px 0" />
              <a-space style="padding: 4px 8px">
                <a-input ref="inputRef" v-model:value="newClassName" placeholder="输入班级名称" />
                <a-button type="text" @click="addClass(newClassName)" :loading="addClassLoading">
                  <template #icon>
                    <plus-outlined />
                  </template>
                  添加班级
                </a-button>
              </a-space>
            </template>
          </a-select>

          <div v-if="!classOptions || classOptions.length === 0" style="margin-left: 10px">
            <a-tag color="warning">当前课程下没有班级</a-tag>
            <a-button type="primary" size="small" style="margin-left: 10px" @click="showAddClassModal">
              <template #icon><PlusOutlined /></template>
              添加班级
            </a-button>
          </div>
        </div>

        <div class="head-right">
          <a-button type="primary" :disabled="!selectedClass" @click="showAddStudent">
            <template #icon><UserAddOutlined /></template>添加学生
          </a-button>
          <a-button type="primary" danger :disabled="!hasSelected" @click="showDeleteStudentConfirm()">
            <template #icon><DeleteOutlined /></template>批量删除
          </a-button>
          <a-button type="primary" :disabled="!hasSelected" @click="visibleMoveStudent = true">
            <template #icon><SwapOutlined /></template>批量调动
          </a-button>
        </div>
      </div>

      <div class="body">
        <template v-if="!pageLoading">
          <div style="padding-top: 10px; width: 20%; border-right: 1px solid rgba(5, 5, 5, 0.06)">
            <div class="team-header">
              <span class="team-title">小组</span>
              <a-button type="primary" size="small" @click="toOpenAddTeamModal">
                <template #icon>
                  <PlusOutlined />
                </template>
                添加小组
              </a-button>
            </div>

            <a-modal v-model:open="visibleAddTeam" title="添加小组" @ok="addTeam">
              <a-input v-model:value="newTeamName" placeholder="输入小组名称" />
            </a-modal>

            <div>
              <a-menu
                class="teams-menu"
                v-model:selectedKeys="selectedTeam"
                theme="light"
              >
                <a-menu-item :key="null" @click="selectTeam(null)">
                  <span class="menu-item-content">
                    <UserOutlined /> 全部学生
                  </span>
                </a-menu-item>

                <a-menu-item
                  v-for="team in teamOptions"
                  :key="team.teamId"
                  @click="selectTeam(team.teamId)"
                >
                  <div class="menu-item-content">
                    <span>
                      <TeamOutlined />
                      {{ team.teamName }}
                    </span>

                    <a-button
                      type="link"
                      danger
                      @click.stop="showDeleteTeamConfirm(team)"
                      class="delete-btn"
                    >
                      <DeleteOutlined />
                    </a-button>
                  </div>
                </a-menu-item>
              </a-menu>
            </div>
          </div>

          <!-- 筛选 -->
          <div style="width: 80%">
            <a-form class="filter" ref="formRef" :model="formState" layout="inline" autocomplete="off">
              <div class="filter-content">
                <div class="filter-options">
                  <a-row :gutter="[16, 8]">
                    <a-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6">
                      <a-form-item label="学生名称" name="userName">
                        <a-input v-model:value="formState.userName" placeholder="输入学生" allow-clear />
                      </a-form-item>
                    </a-col>
                    <a-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6">
                      <a-form-item label="学生ID" name="studentId">
                        <a-input v-model:value="formState.studentId" placeholder="输入ID" allow-clear />
                      </a-form-item>
                    </a-col>
                    <a-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6">
                      <a-form-item label="学号" name="studentNo">
                        <a-input v-model:value="formState.studentNo" placeholder="输入学号" allow-clear />
                      </a-form-item>
                    </a-col>
                    <a-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6">
                      <a-form-item label="学院" name="college">
                        <a-input v-model:value="formState.college" placeholder="输入学院" allow-clear />
                      </a-form-item>
                    </a-col>
                    <a-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6">
                      <a-form-item label="专业" name="major">
                        <a-input v-model:value="formState.major" placeholder="输入专业" allow-clear />
                      </a-form-item>
                    </a-col>
                    <a-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6">
                      <a-form-item label="班级" name="className">
                        <a-input v-model:value="formState.className" placeholder="输入班级" allow-clear />
                      </a-form-item>
                    </a-col>
                    <a-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6">
                      <a-form-item label="分组状态" name="type">
                        <a-select ref="select" v-model:value="formState.haveTeam" style="width: 120px">
                          <a-select-option :value="undefined">全部</a-select-option>
                          <a-select-option :value="1">已分组</a-select-option>
                          <a-select-option :value="0">未分组</a-select-option>
                        </a-select>
                      </a-form-item>
                    </a-col>
                  </a-row>
                </div>

                <div class="filter-buttons">
                  <a-button
                    type="primary"
                    :disabled="!(hasSelected && selectedTeam[0] != null)"
                    @click="setTeamLeader()"
                  >
                    <template #icon><CrownOutlined /></template>设为组长
                  </a-button>
                  <a-button type="primary" @click="findClassStudents()">
                    <template #icon><SearchOutlined /></template>查询
                  </a-button>
                </div>
              </div>
            </a-form>

            <div class="table-container">
              <a-table
                :pagination="false"
                :row-selection="{ selectedRowKeys: state.selectedRowKeys, onChange: onSelectChange }"
                :columns="columns"
                :data-source="studentList"
                :loading="tableLoading"
                rowKey="userId"
                :scroll="{ y: 'calc(70vh - 240px)' }"
                size="middle"
              >
                <template #bodyCell="{ record, column, text }">
                  <template v-if="column.dataIndex === 'teamLeadingId'">
                    <a-tag v-if="record.teamId == null" color="default">未分组</a-tag>
                    <a-tag v-else-if="record.userId == record.teamLeaderId" color="green">组长</a-tag>
                    <a-tag v-else color="blue">组员</a-tag>
                  </template>
                </template>
                <template #emptyText>
                  <span>{{ tableLoading ? '加载中...' : '暂无数据' }}</span>
                </template>
              </a-table>
              
              <div class="pagination-wrapper">
                <a-pagination
                  v-model:current="current"
                  v-model:page-size="pageSizeRef"
                  :total="total"
                  show-size-changer
                  :show-total="(total) => `共 ${total} 条记录`"
                />
              </div>
            </div>
          </div>
        </template>
      </div>
    </a-spin>
  </div>
  <contextHolder />
      <AddStudentModal
      v-model:model-visible="visibleAddStudent"
      :class-id="selectedClass"
      @confirm="onAddStudentConfirm"
    />
    
    <MoveStudentModal
      v-model:model-visible="visibleMoveStudent"
      :classId="selectedClass"
      :teams="teamOptions"
      :students="state.selectedRowKeys"
      @confirm="findClassStudents()"
    />

  <!-- 添加班级模态框 -->
  <a-modal
    v-model:open="visibleAddClass"
    title="添加班级"
    @ok="handleAddClassOk"
    :confirmLoading="addClassLoading"
    @cancel="() => { visibleAddClass = false; newClassName = ''; }"
  >
    <a-form layout="vertical">
      <a-form-item 
        label="班级名称" 
        name="className"
        :rules="[{ required: true, message: '请输入班级名称' }]"
      >
        <a-input v-model:value="newClassName" placeholder="请输入班级名称" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
import { useStore } from 'vuex';
import { message, Modal } from 'ant-design-vue';
import { 
  DeleteOutlined, 
  PlusOutlined, 
  TeamOutlined, 
  SearchOutlined, 
  UserOutlined, 
  UserAddOutlined, 
  SwapOutlined,
  CrownOutlined,
  InfoCircleOutlined
} from '@ant-design/icons-vue';
import ClassDao from '@/daos/class_dao';
import UserDao from '@/daos/user_dao';
import TeamDao from '@/daos/team_dao';
import MoveStudentModal from './MoveStudentModal.vue';
import AddStudentModal from './AddStudentModal.vue';
import { useRoute, useRouter } from 'vue-router';
import { ref, reactive, computed, watch, onMounted, defineComponent } from 'vue';

const store = useStore();
const route = useRoute();
const router = useRouter();
const [modal, contextHolder] = Modal.useModal();

const classDao = new ClassDao();
const userDao = new UserDao();
const teamDao = new TeamDao();

// 加载状态管理

// 窗口开关
const visibleAddTeam = ref<boolean>(false);
const visibleAddStudent = ref<boolean>(false);
const visibleImportStudent = ref<boolean>(false);
const visibleMoveStudent = ref<boolean>(false);
const visibleAddClass = ref<boolean>(false);

const VNodes = defineComponent({
  props: {
    vnodes: {
      type: Object,
      required: true
    }
  },
  render() {
    return this.vnodes;
  }
});

// 加载状态
const addClassLoading = ref(false);
const pageLoading = ref(true);
const tableLoading = ref(false);

// 获取课程ID - 优先从路由参数获取，后备从store获取
const courseId = computed(() => {
  // 优先从路由参数获取
  const routeId = route.params.courseId ? Number(route.params.courseId) : null;
  
  // 如果路由参数中没有，尝试从store获取
  const storeId = store.state.course.courseId;
  
  const id = routeId || storeId;
  console.log(`人员管理页面 - 课程ID: ${id} (路由参数: ${routeId}, store: ${storeId})`);
  
  return id;
});

// 班级和小组选项
const classOptions = ref([]);
const teamOptions = ref([]);

// 班级选中对象
const selectedClass = ref(null);
// 小组选中对象
const selectedTeam = ref([null]); // 默认选中"全部"

// 添加班级
const newClassName = ref('');
const addClass = (newName) => {
  if (!newName) {
    message.info('班级名称不能为空');
    return;
  }
  
  if (!courseId.value) {
    message.error('课程ID不存在，无法添加班级');
    return;
  }
  
  const hide = message.loading('正在添加班级...', 0);
  
  classDao
    .addClass(courseId.value, newName)
    .then((result) => {
      hide();
      if (result?.data?.code === 200) {
        message.success('添加班级成功');
        findClass();
        newClassName.value = '';
        visibleAddClass.value = false;
      } else {
        message.error(result?.data?.msg || '添加班级失败');
      }
    })
    .catch(error => {
      hide();
      console.error('添加班级失败:', error);
      message.error('添加班级失败，请检查网络连接');
    })
    .finally(() => {
      addClassLoading.value = false;
    });
};

// 删除班级
const deleteClass = (classId) => {
  if (!classId) {
    message.warning('班级ID不存在，无法删除');
    return;
  }
  
  const hide = message.loading('正在删除班级...', 0);
  
  classDao
    .deleteClass(classId)
    .then((result) => {
      hide();
      if (result?.data?.code === 200) {
        message.success('删除班级成功');
        findClass();
        selectedClass.value = undefined;
        studentList.value = [];
        total.value = 0;
      } else {
        message.error(result?.data?.msg || '删除班级失败');
      }
    })
    .catch(error => {
      hide();
      console.error('删除班级失败:', error);
      message.error('删除班级失败，请检查网络连接');
    });
};

// 删除班级内的学生
const deleteClassStudent = () => {
  if (!selectedClass.value || !state.selectedRowKeys.length) {
    message.warning('未选择班级或学生，无法删除');
    return;
  }
  
  const hide = message.loading('正在删除学生...', 0);
  
  classDao
    .deleteClassStudentRef(selectedClass.value, state.selectedRowKeys)
    .then((result) => {
      hide();
      if (result?.data?.code === 200) {
        message.success('删除学生成功');
        findClassStudents();
        state.selectedRowKeys = [];
      } else {
        message.error(result?.data?.msg || '删除学生失败');
      }
    })
    .catch(error => {
      hide();
      console.error('删除学生失败:', error);
      message.error('删除学生失败，请检查网络连接');
    });
};

// 选择小组
const selectTeam = (teamId) => {
  selectedTeam.value = [teamId];
  findClassStudents();
};

// 设置组长
const setTeamLeader = () => {
  if (!state.selectedRowKeys || state.selectedRowKeys.length === 0) {
    message.info('请先选择一位学生');
    return;
  }
  
  if (state.selectedRowKeys.length > 1) {
    message.info('小组组长只能设置一位，请只选择一位学生');
    return;
  }
  
  if (!selectedTeam.value || !selectedTeam.value[0]) {
    message.info('请先选择一个小组');
    return;
  }
  
  // 检查选中的学生是否在当前小组中
  const selectedStudent = studentList.value.find(student => student.userId === state.selectedRowKeys[0]);
  if (!selectedStudent) {
    message.error('无法找到选中的学生信息');
    return;
  }
  
  if (selectedStudent.teamId !== selectedTeam.value[0]) {
    message.warning('只能将当前小组内的学生设置为组长');
    return;
  }
  
  // 如果该学生已经是组长，提示用户
  if (selectedStudent.userId === selectedStudent.teamLeaderId) {
    modal.confirm({
      title: '确认操作',
      content: '该学生已经是组长，是否重新设置？',
      okText: '确认',
      cancelText: '取消',
      onOk() {
        performSetTeamLeader(selectedTeam.value[0], state.selectedRowKeys[0]);
      }
    });
    return;
  }
  
  // 执行设置组长操作
  performSetTeamLeader(selectedTeam.value[0], state.selectedRowKeys[0]);
};

// 执行设置组长操作的函数
const performSetTeamLeader = (teamId, userId) => {
  const hide = message.loading('正在设置组长...', 0);
  
  teamDao
    .setTeamLeader(teamId, userId)
    .then((result) => {
      hide();
      if (result?.data?.code === 200) {
        message.success(result?.data?.msg || '设置组长成功');
        findClassStudents(); // 重新加载学生数据以更新UI
      } else {
        message.error(result?.data?.msg || '设置组长失败');
      }
    })
    .catch(error => {
      hide();
      console.error('设置组长失败:', error);
      message.error('设置组长失败，请检查网络连接');
    });
};

// 打开新增小组窗口
const toOpenAddTeamModal = () => {
  if (!selectedClass.value) {
    message.info('请先选择班级');
    return;
  }
  visibleAddTeam.value = true;
};

// 添加小组
const newTeamName = ref('');
const addTeam = () => {
  if (!newTeamName.value) {
    message.info('小组名称不能为空');
    return;
  }
  
  if (!selectedClass.value) {
    message.info('请先选择班级');
    return;
  }
  
  const hide = message.loading('正在添加小组...', 0);
  
  teamDao
    .addTeam(selectedClass.value, newTeamName.value)
    .then(async (result) => {
      hide();
      if (result?.data?.code === 200) {
        message.success('添加小组成功');
        await findClass();
        selectClass(selectedClass.value);
        visibleAddTeam.value = false;
        newTeamName.value = '';
      } else {
        message.error(result?.data?.msg || '添加小组失败');
      }
    })
    .catch(error => {
      hide();
      console.error('添加小组失败:', error);
      message.error('添加小组失败，请检查网络连接');
      visibleAddTeam.value = false;
    });
};

// 删除小组
const deleteTeam = (teamId) => {
  if (!teamId) {
    message.warning('小组ID不存在，无法删除');
    return;
  }
  
  const hide = message.loading('正在删除小组...', 0);
  
  teamDao
    .deleteTeam(teamId)
    .then(async (result) => {
      hide();
      if (result?.data?.code === 200) {
        message.success('删除小组成功');
        await findClass();
        selectClass(selectedClass.value);
        selectedTeam.value = [null];
      } else {
        message.error(result?.data?.msg || '删除小组失败');
      }
    })
    .catch(error => {
      hide();
      console.error('删除小组失败:', error);
      message.error('删除小组失败，请检查网络连接');
    });
};

// 删除小组确认框
const showDeleteTeamConfirm = (team) => {
  if (!team || !team.teamId) {
    message.info('小组信息不完整，无法操作');
    return;
  }
  
  modal.confirm({
    title: '移除小组成员',
    content: `确定要移除小组 "${team.teamName}" 及其所有成员吗？该操作只会将学生从小组中移除，不会将学生从班级中删除。`,
    okText: '确认移除',
    okType: 'primary',
    cancelText: '取消',
    onOk() {
      teamDao.deleteTeam(team.teamId)
        .then(result => {
          if (result?.data?.code === 200) {
            message.success(result?.data?.msg || '成功从小组中移除学生，学生仍保留在班级中');
            findClass();
            selectedTeam.value = [null]; // 重置选择为全部
            findClassStudents();
          } else {
            message.error(result?.data?.msg || '操作失败');
          }
        })
        .catch(error => {
          console.error('移除小组成员失败:', error);
          message.error('移除小组成员失败，请检查网络连接');
        });
    }
  });
};

// 删除班级确认框
const showDeleteClassConfirm = (classId, className) => {
  modal.confirm({
    title: '确认删除',
    content: `确定要删除班级 "${className}" 吗？这将同时删除班级下的所有学生关联`,
    okText: '确认',
    okType: 'danger',
    cancelText: '取消',
    onOk() {
      deleteClass(classId);
    }
  });
};

// 删除学生确认框
const showDeleteStudentConfirm = () => {
  if (!state.selectedRowKeys.length) {
    message.info('请至少选择一名学生');
    return;
  }
  
  modal.confirm({
    title: '确认删除',
    content: `确定要从班级中删除选中的 ${state.selectedRowKeys.length} 名学生吗？`,
    okText: '确认',
    okType: 'danger',
    cancelText: '取消',
    onOk() {
      deleteClassStudent();
    }
  });
};

// 显示添加学生模态框
const showAddStudent = () => {
  if (!selectedClass.value) {
    message.warning('请先选择一个班级');
    return;
  }
  
  visibleAddStudent.value = true;
};

// 选择班级后的处理
const selectClass = async (classId) => {
  if (!classId) {
    console.warn('未选择班级');
    return;
  }
  
  console.log(`选择班级: ${classId}`);
  selectedClass.value = classId;
  
  // 当选择新班级时，清空之前的选择
  state.selectedRowKeys = [];
  
  // 获取当前班级下的小组列表
  const currentClass = classOptions.value.find(item => item.classId === classId);
  if (currentClass && currentClass.teamList) {
    teamOptions.value = currentClass.teamList || [];
    console.log(`班级${classId}有${teamOptions.value.length}个小组`);
  } else {
    teamOptions.value = [];
    console.log(`班级${classId}没有小组`);
  }
  
  // 重置小组选择为全部
  selectedTeam.value = [null];
  
  // 加载班级学生
  tableLoading.value = true;
  try {
    await findClassStudents();
    console.log('成功加载班级学生数据');
  } catch (error) {
    console.error('加载班级学生数据失败:', error);
    message.error('加载班级学生失败，请检查网络连接');
    studentList.value = [];
    total.value = 0;
  } finally {
    tableLoading.value = false;
  }
};

// 筛选表单
const formState = reactive({
  userName: '',
  studentId: undefined,
  studentNo: '',
  college: '',
  major: '',
  className: '',
  haveTeam: null
});

// 表格相关
const studentList = ref([]);
const columns = [
  { title: '姓名', dataIndex: 'userName', align: 'center' },
  { title: '学号', dataIndex: 'studentNo', align: 'center' },
  { title: '学院', dataIndex: 'college', align: 'center' },
  { title: '专业', dataIndex: 'major', align: 'center' },
  { title: '班级', dataIndex: 'className', align: 'center' },
  { title: '小组', dataIndex: 'teamName', align: 'center' },
  { title: '身份', dataIndex: 'teamLeadingId', align: 'center' }
];

// 表格多选
const state = reactive<{
  selectedRowKeys: number[];
}>({
  selectedRowKeys: []
});
const onSelectChange = (selectedRowKeys: []) => {
  state.selectedRowKeys = selectedRowKeys;
};
const hasSelected = computed(() => state.selectedRowKeys.length > 0);

// 分页
const current = ref(1);
const pageSizeRef = ref(10);
const total = ref(0);

// 获取班级信息
const findClass = async () => {
  const id = courseId.value;
  if (!id) {
    console.error('课程ID不存在，无法加载班级信息');
    message.error('无法获取课程信息，请确认URL是否正确或从课程列表重新进入');
    pageLoading.value = false;
    return;
  }
  
  console.log(`开始获取课程(${id})的班级信息`);
  pageLoading.value = true;
  
  try {
    const result = await classDao.findClassByCourseId(id);
    console.log('获取班级信息结果:', result);
    
    if (result?.data?.code === 200 && result?.data?.data) {
      classOptions.value = result.data.data || [];
      console.log(`成功获取${classOptions.value.length}个班级信息`);
      
      // 如果有班级，默认选择第一个班级
      if (classOptions.value.length > 0) {
        selectedClass.value = classOptions.value[0].classId;
        console.log(`自动选择第一个班级: ${selectedClass.value}`);
        selectClass(selectedClass.value);
      } else {
        console.log('该课程下没有班级');
        studentList.value = [];
        total.value = 0;
        teamOptions.value = [];
      }
    } else {
      console.warn('获取班级数据异常:', result);
      classOptions.value = [];
      studentList.value = [];
      total.value = 0;
      teamOptions.value = [];
      
      if (result?.data?.msg) {
        message.warning(result.data.msg);
      } else {
        message.warning('未找到班级数据');
      }
    }
  } catch (error) {
    console.error('获取班级信息失败:', error);
    message.error('加载班级信息失败，请检查网络连接');
    classOptions.value = [];
    studentList.value = [];
    total.value = 0;
    teamOptions.value = [];
  } finally {
    pageLoading.value = false;
  }
};

// 获取学生数据
const findClassStudents = async () => {
  if (!selectedClass.value) {
    console.warn('未选择班级，无法加载学生数据');
    studentList.value = [];
    total.value = 0;
    return;
  }
  
  console.log(`开始获取班级(${selectedClass.value})的学生数据，小组筛选:`, selectedTeam.value[0]);
  tableLoading.value = true;
  
  try {
    const result = await userDao.findClassStudents(
      selectedClass.value,
      selectedTeam.value[0],
      formState.studentId,
      formState.userName,
      formState.haveTeam,
      current.value,
      pageSizeRef.value,
      formState.studentNo,
      formState.college,
      formState.major,
      formState.className
    );
    
    console.log('学生数据加载结果:', result);
    
    if (result?.data?.code === 200 && result?.data?.data) {
      studentList.value = result.data.data.rows || [];
      total.value = result.data.data.totalCount || 0;
      console.log(`成功获取${studentList.value.length}个学生数据，总数:${total.value}`);
      
      // 如果没有学生数据，显示提示
      if (studentList.value.length === 0) {
        if (selectedTeam.value[0]) {
          message.info('该小组下没有学生数据');
        } else {
          message.info('该班级下没有学生数据，请添加学生');
        }
      }
    } else {
      console.warn('获取学生数据异常:', result);
      studentList.value = [];
      total.value = 0;
      if (result?.data?.msg) {
        message.warning(result.data.msg);
      } else {
        message.warning('未能获取学生数据');
      }
    }
  } catch (error) {
    console.error('加载学生数据失败:', error);
    message.error('加载学生数据失败，请检查网络连接');
    studentList.value = [];
    total.value = 0;
  } finally {
    tableLoading.value = false;
  }
};

// 重新加载页面
const reload = () => {
  pageLoading.value = true;
  
  // 确保courseId被保存到store中
  if (courseId.value) {
    store.commit('course/SET_COURSEID', courseId.value);
    console.log(`已将courseId(${courseId.value})保存到store中`);
  }
  
  // 重新加载数据
  findClass().then(() => {
    if (selectedClass.value) {
      findClassStudents();
    }
  }).catch(error => {
    console.error('加载数据失败:', error);
    message.error('加载数据失败，请刷新页面重试');
  });
};

// 在组件挂载时初始化数据
onMounted(() => {
  // 如果路由中没有课程ID，检查store
  if (!route.params.courseId && !store.state.course.courseId) {
    console.error('无法获取课程ID，请从课程列表进入');
    message.error('无法获取课程信息，请从课程列表重新进入');
    router.push('/course/list');
    return;
  }
  
  console.log(`人员管理页面已加载，课程ID: ${courseId.value}`);
  
  // 保存当前课程ID到store，确保其他组件可以访问
  if (courseId.value) {
    store.commit('course/SET_COURSEID', courseId.value);
  }
  
  // 加载数据
  reload();
});

// 监听分页变化
watch(
  [() => current.value, () => pageSizeRef.value],
  () => {
    if (selectedClass.value) {
      findClassStudents();
    }
  }
);

// 监听路由变化，当课程ID变化时重新加载
watch(
  () => route.params.courseId,
  (newId) => {
    if (newId && newId !== store.state.course.courseId?.toString()) {
      console.log(`课程ID变更为: ${newId}，重新加载数据`);
      store.commit('course/SET_COURSEID', Number(newId));
      reload();
    }
  }
);

// 监听store中的课程ID变化
watch(
  () => store.state.course.courseId,
  (newId) => {
    if (newId && !route.params.courseId) {
      console.log(`Store中课程ID更新为: ${newId}，重新加载数据`);
      reload();
    }
  }
);

// 添加班级模态框
const handleAddClassOk = () => {
  if (!newClassName.value) {
    message.info('班级名称不能为空');
    return;
  }
  
  addClass(newClassName.value);
};

// 显示添加班级模态框
const showAddClassModal = () => {
  visibleAddClass.value = true;
};

// 添加学生确认回调
const onAddStudentConfirm = () => {
  findClassStudents();
};
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  padding: 1%;
  height: 100%;
  min-width: 1280px;
  overflow: auto;
}

.head {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  padding: 1.5%;
  margin-bottom: 1%;
  height: auto;
  width: 100%;
  min-height: 70px;
  align-items: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  background-color: #fff;
}

.head-left {
  display: flex;
  align-items: center;
}

.head-right {
  display: flex;
  gap: 8px;
}

.body {
  display: flex;
  flex-direction: row;
  padding: 0.5%;
  height: 90%;
  width: 100%;
  min-height: 540px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  background-color: #fff;
  overflow: hidden;
}

.team-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 16px 16px;
  border-bottom: 1px solid #f0f0f0;
}

.team-title {
  font-size: 16px;
  font-weight: 500;
}

.teams-menu {
  height: calc(75vh - 120px);
  border: 0;
  overflow-y: auto;
}

.menu-item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.delete-btn {
  opacity: 0;
  transition: opacity 0.2s;
}

.menu-item-content:hover .delete-btn {
  opacity: 1;
}

/*删除按钮样式*/
.confirmButton {
  background-color: transparent;
  border: none;
}

.class-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.filter {
  padding: 16px;
  background-color: #fafafa;
  border-radius: 8px;
  margin-bottom: 16px;
}

.filter-content {
  width: 100%;
  display: flex;
  flex-direction: column;
}

.filter-options {
  width: 100%;
}

.filter-buttons {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
  margin-top: 16px;
}

.table-container {
  display: flex;
  flex-direction: column;
  height: calc(100% - 240px);
}

.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  padding: 16px 0;
}

.empty-state {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}
</style>
